<?php
//by willson 105328468@qq.com 2014/10/11
//index page interface

class recharge extends core {
	private $recharge_mod;
	public function __construct() {
		$this->recharge_mod = m("recharge");
		parent::__construct();
	}

	//充值列表
	public function index() {
		$recharge_mod = m("recharge");
		$sql = "SELECT * FROM {$this->tbp}recharge WHERE status='1' ORDER BY price ASC";
		$recharges = $this->db->get_results($sql);
		if ($recharges) {
			foreach ($recharges as $k => $recharge) {
				$recharges[$k]->recharged_money = $this->recharge_mod->recharged_money($recharge);
				$recharges[$k]->bonus = $recharge->recharged_money - $recharge->price;
			}
		}
		$sql = "SELECT money FROM {$this->tbp}member WHERE id='{$this->member_id}'";
		$money = floatval($this->db->get_var($sql));
		success(array( 'recharges'=>$recharges, 'money'=>$money ));
	}

	//20171221 by @jsong 弃用，使用member/money_history代替
	//充值明细
	public function history() {
		$type = (isset($_GET['type']) && trim($_GET['type'])) ? trim($_GET['type']) : 'recharge';
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 15;
		if ($type=="order") {
			//$histories = null;
			$sql = "SELECT id, add_time FROM {$this->tbp}order WHERE member_id='{$this->member_id}'
				AND pay_method='yue' AND status<>0 ORDER BY id DESC LIMIT {$offset},{$pagesize}";
			$orders = $this->db->get_results($sql);
			if ($orders) {
				foreach ($orders as $k => $order) {
					//$sql = "SELECT project_name FROM {$this->tbp}order_project WHERE order_id='{$order->id}'";
					//$project_name = $this->db->get_var($sql);
					$orders[$k]->content = "使用余额";
					$orders[$k]->add_time = date("Y-m-d H:i:s", $order->add_time);
				}
			}
			success($orders);
		} else {
			$sql = "SELECT id, recharge_id, price, bonus, add_time, '' as content FROM {$this->tbp}member_recharge WHERE member_id='{$this->member_id}'
				AND status='1' ORDER BY id DESC LIMIT {$offset},{$pagesize}";
			$histories = $this->db->get_results($sql);
			if ($histories) {
				foreach ($histories as $k => $h) {
					$histories[$k]->add_time = date("Y-m-d H:i:s", $h->add_time);
					$content = "充值{$h->price}";
					if ($h->bonus) {
						$content .= "送{$h->bonus}";
					}
					$histories[$k]->content = $content;
				}
			}
			success($histories);
		}
	}

	//结算页面
	public function jiesuan() {
		$id = (isset($_GET['id']) && intval($_GET['id'])) ? intval($_GET['id']) : 0;
		if ($id<=0) error("找不到此记录");
		$sql = "SELECT * FROM {$this->tbp}recharge WHERE id='{$id}' AND status='1'";
		$recharge = $this->db->get_row($sql);
		if (!$recharge) error("找不到此记录");
		$recharge->recharged_money = $this->recharge_mod->recharged_money($recharge);
		$recharge->bonus = $recharge->recharged_money - $recharge->price;
		success($recharge);
	}

	//购买
	public function buy($is_show=true) {
		$status = 0;
		$id = (isset($_POST['id']) && intval($_POST['id'])) ? intval($_POST['id']) : 0;
		$pay_method = (isset($_POST['pay_method']) && trim($_POST['pay_method'])) ? trim($_POST['pay_method']) : 'alipay';
		$pay_method_name = (isset($_POST['pay_method_name']) && trim($_POST['pay_method_name'])) ? trim($_POST['pay_method_name']) : '';
		$sql = "SELECT * FROM {$this->tbp}recharge WHERE id='{$id}' AND status='1'";
		$recharge = $this->db->get_row($sql);
		if (!$recharge) error("找不到此记录");
		if ($recharge) {
			$recharge->recharged_money = $this->recharge_mod->recharged_money($recharge);
			$recharge->bonus = $recharge->recharged_money - $recharge->price;
		}
		//余额支付
		/*
		if ($pay_method=="yue") {
			if ($_SESSION['member']->money >= $recharge->price) {
				$remain = $_SESSION['member']->money - $recharge->price;
				$sql = "UPDATE {$this->tbp}member SET money='{$remain}' WHERE id='{$this->member_id}'";
				$this->db->query($sql);
				$_SESSION['member']->money = $remain;
				$status = 1;
			} else {
				error("您的余额不足以支付");
			}
		}
		*/
		//
		$order_sn = "CZ".generate_order_sn();
		$sql = "INSERT INTO {$this->tbp}member_recharge(recharge_id, member_id, price, recharged_money, order_sn,
			bonus, pay_method, status, add_time, pay_time)
			VALUES('{$id}', '{$this->member_id}', '{$recharge->price}', '{$recharge->recharged_money}', '{$order_sn}',
			'{$recharge->bonus}', '{$pay_method}', '{$status}', '".time()."', '0')";
		$this->db->query($sql);
		$order_id = $this->db->insert_id;
		//要写入session，by willson 2015/9/2
		$_SESSION['order_sn'] = $order_sn;
		$_SESSION['order_price'] = $recharge->price;
		$_SESSION['total_price'] = $recharge->price;
		$_SESSION['pay_method_name'] = $pay_method_name;
		if ($is_show) {
			success(array("status"=>$status, "order_id"=>$order_id, "order_sn"=>$order_sn, "total_price"=>$recharge->price));
		}
	}

	//下单接口,微信端用,因为涉及到需要即时跳转去支付
	public function order_pay() {
		//判断是否从结算那里提交过来，如果是，表示是新订单，清空订单SESSION
		$order_sn = (isset($_SESSION['order_sn']) && trim($_SESSION['order_sn'])) ? trim($_SESSION['order_sn']) : '';
		$order_price = (isset($_SESSION['order_price']) && trim($_SESSION['order_price'])) ? floatval($_SESSION['order_price']) : 0;
		$pay_method_name = (isset($_SESSION['pay_method_name']) && trim($_SESSION['pay_method_name'])) ? trim($_SESSION['pay_method_name']) : '';
		$order_body = WEB_TITLE.' - 会员充值';
		if ($order_sn=='' || $order_price<=0) {
			$this->buy(false);
			$order_sn = (isset($_SESSION['order_sn']) && trim($_SESSION['order_sn'])) ? trim($_SESSION['order_sn']) : '';
			$order_price = (isset($_SESSION['order_price']) && trim($_SESSION['order_price'])) ? floatval($_SESSION['order_price']) : 0;
		}
		if ($order_sn=='' || $order_price<=0) {
			error('订单信息错误！');
		}

		include_once(FRAMEWORK_PATH . "/class/wxapi/WxPayPubHelper/WxPayPubHelper.php");

		//使用jsapi接口
		$jsApi = new JsApi_pub();

		//=========步骤1：网页授权获取用户openid============
		//通过code获得openid
		$openid = '';
		$code = (isset($_GET['code']) && trim($_GET['code'])) ? trim($_GET['code']) : '';
		if (!$code){
			//触发微信返回code码
			$url = $jsApi->createOauthUrlForCode(urlencode(https().$_SERVER['SERVER_NAME']."/wap.php?app=recharge&act=order_pay"));
			//echo $url;
			//exit;
			header("Location: {$url}");
			exit;
		}else{
			//获取code码，以获取openid
			$jsApi->setCode($code);
			$openid = $jsApi->getOpenid();
		}

		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		$unifiedOrder = new UnifiedOrder_pub();

		$unifiedOrder->setParameter("openid", "$openid");
		$unifiedOrder->setParameter("body", "$order_body");//商品描述
		if($order_sn==''){
			//自定义订单号，此处仅作举例
			$timeStamp = time();
			$order_sn = WxPayConf_pub::APPID."$timeStamp";
		}
		$unifiedOrder->setParameter("out_trade_no", "$order_sn");//商户订单号
		$unifiedOrder->setParameter("total_fee", $order_price*100);//总金额,单位:分
		$unifiedOrder->setParameter("notify_url", "http://".$_SERVER['SERVER_NAME']."/wx_notify_url.php");//通知地址
		$unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型


		$prepay_id = $unifiedOrder->getPrepayId();
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);

		$jsApiParameters = $jsApi->getParameters();
		success($jsApiParameters, '成功', 0, array("order_sn"=>$order_sn, "total_price"=>$order_price, "pay_method_name"=>$pay_method_name));
	}

}
